// 雨滴数
var rains = []
var count = 60
var timers = null

// 雨滴对象
function Rain() {}

Rain.prototype = {
  init: function (w, h) {
    this.x = Random(0, w)
    this.y = 0
    this.floor = Random(h * 0.8, h * 0.9)
    this.ySpeed = 2
    this.yAcceleration = 2
    this.width = Random(2, 3)
    this.height = 10
    this.transparent = 1
    this.radius = 0
    this.maxRadius = this.width * 15
    this.tChange = 0.95
    this.time = 0
  },
  draw: function (w, h, ctx) {
    if (this.y >= this.floor) {
      // 绘制圆圈
      ctx.beginPath()
      ctx.strokeStyle = 'rgba(0, 255, 255,' + this.transparent + ')'
      ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false)
      ctx.stroke()
    } else {
      // 绘制雨滴
      ctx.fillStyle = '#66ffff'
      ctx.fillRect(this.x, this.y, this.width, this.height)
    }
    this.update(w, h)
  },
  update: function (w, h) {
    // 判断需要变化雨滴还是变化圆圈

    // 变化雨滴
    if (this.y >= this.floor) {
      // 圆圈变透明
      this.radius++
      if (this.radius >= this.maxRadius) {
        //   透明度变化
        if (this.transparent >= 0.03) {
          this.transparent *= this.tChange
        } else {
          this.init(w, h)
        }
      }
    } else {
      this.y += this.ySpeed + this.yAcceleration * this.time
    }
  }
}

// 创建随机数
function Random(min, max) {
  return Math.random() * (max - min) + min
}

// 创建雨滴
//
function creatRains(w, h) {
  for (var i = 0; i < count; i++) {
    ;(function (j) {
      setTimeout(function () {
        var rain = new Rain()
        rain.init(w, h)
        rains.push(rain)
      }, j * 200)
    })(i)
  }
}

// var rain = new Rain();
// rain.init();

// 开始下雨
function move(w, h, ctx) {
  ctx.fillStyle = 'rgba(0, 0, 0, 0.2)'
  ctx.fillRect(0, 0, w, h)

  for (var i = 0; i < rains.length; i++) {
    rains[i].draw(w, h, ctx)
    rains[i].time += 0.01
  }

  // 会栈溢出
  //   requestAnimationFrame(move(w, h, ctx))
}

function star(w, h, ctx) {
  creatRains(w, h)

  timers = setInterval(() => {
    move(w, h, ctx)
  }, 60)
}

function stop() {
  clearInterval(timers)
}

export default {
  star,
  stop
}
